<?php


namespace addons\ymystripe\controller;


use app\common\controller\Api;
use Stripe\Stripe;
use Stripe\Webhook;

class Payment extends Api
{
    protected $noNeedLogin = ['notify'];

    public function notify(){
        $config = get_addon_config('ymystripe');
        Stripe::setApiKey($config['secret']);

        $endpoint_secret = $config['sign'];

        $payload = @file_get_contents('php://input');
        $sig_header = $_SERVER['HTTP_STRIPE_SIGNATURE'];
        $event = null;

        try {
            $event = Webhook::constructEvent(
                $payload, $sig_header, $endpoint_secret
            );
        } catch(\UnexpectedValueException $e) {
            // Invalid payload
            http_response_code(400);
            exit();
        } catch(\Stripe\Exception\SignatureVerificationException $e) {
            // Invalid signature
            http_response_code(400);
            exit();
        }
        switch ($event->type) {
            case 'charge.succeeded':
                $succeeded = $event->data->object;
                if ($succeeded->status == 'succeeded'){
                    //目前先直接拿金额进行对比，后续再考虑汇率换算
                    $pay = model('app\api\model\wanlshop\Pay')->get(['payment_intent' => $succeeded->payment_intent]);
                    if ($pay['price'] * 100 == $succeeded->amount){
                        $pay->allowField(true)->save([
                            'pay_state' => 1,
                            'pay_type' => 3,
                        ]);
                        model('app\api\model\wanlshop\Order')->allowField(true)->save([
                            'id' => $pay['order_id'],
                            'state'  => 2,
                            'paymenttime' => time()
                        ]);
                    }
                }
                break;
            default:
                // Unexpected event type
                http_response_code(400);
                exit();
        }

        http_response_code(200);

    }
}